package com.sj.uabrowser.mvp.menu.view.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.classic.common.MultipleStatusView;
import com.orhanobut.logger.Logger;
import com.sj.uabrowser.R;
import com.sj.uabrowser.app.CallOtherOpeanFile;
import com.sj.uabrowser.db.FileInfo;
import com.sj.uabrowser.db.gen.FileInfoDao;
import com.sj.uabrowser.framework.BasePresenter;
import com.sj.uabrowser.framework.LazyLoadFragment;
import com.sj.uabrowser.mvp.menu.service.DownloadService;
import com.sj.uabrowser.mvp.menu.view.act.DownloadAct;
import com.sj.uabrowser.mvp.menu.view.adp.DownloadDoneAdp;
import com.sj.uabrowser.mvp.menu.view.adp.DownloadingAdp;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class DownloadDoneFragment extends LazyLoadFragment {


    private static DownloadDoneFragment sDownloadDoneFragment;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.multipleStatusView)
    MultipleStatusView multipleStatusView;
    @BindView(R.id.ll_bottom_edit)
    LinearLayout llBottomEdit;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    List<FileInfo> fileList = new ArrayList<>();
    private boolean isEdit = false;
    private FileInfoDao fileInfoDao;
    private DownloadDoneAdp adp;

    public static DownloadDoneFragment getInstance(String title) {
        if (sDownloadDoneFragment == null) {
            sDownloadDoneFragment = new DownloadDoneFragment();
            Bundle bundle = new Bundle();
            bundle.putString("title", title);
            sDownloadDoneFragment.setArguments(bundle);
        }
        return sDownloadDoneFragment;
    }

    @Override
    protected int setContentView() {
        return R.layout.fragment_download_done;
    }

    @Override
    protected void lazyLoad() {
        fileList.clear();
        fileInfoDao = daoSession.getFileInfoDao();
        List<FileInfo> files = fileInfoDao.queryRaw("where finished = length");
        for (int i = 0; i < files.size(); i++) {
            FileInfo bean = files.get(i);
            String filename = bean.getFileName();
            File file =new File(DownloadService.DOWNLOAD_PATH,filename);
            if(!file.exists()){
                fileInfoDao.delete(bean);
                files.remove(bean);
            }
        }

        fileList.addAll(files);
        Set<String> parentDatas = new HashSet<>();
        for (int i = 0; i < fileList.size(); i++) {
            FileInfo bean = fileList.get(i);
            long date = bean.getDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String time = sdf.format(date);
            if (!parentDatas.contains(time)) {
                bean.setTime(time);
                parentDatas.add(time);
            }else{
                bean.setTime("");
            }
        }
        isEdit = false;
        ((DownloadAct)act).tvEdit.setText("管理");
        adp.notifyDataSetChanged();
        if(fileList.size()==0){
            ((DownloadAct)act).tvEdit.setText("");
            multipleStatusView.showEmpty();
            onBackMain();
        }
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void setView() {
        rv.setLayoutManager(new LinearLayoutManager(act));
        adp = new DownloadDoneAdp(R.layout.common_list_item_downloaddone, fileList);
        rv.setAdapter(adp);
        adp.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FileInfo fileInfo = fileList.get(position);
                if (!isEdit) {
                    new CallOtherOpeanFile().openFile(act, new File(DownloadService.DOWNLOAD_PATH, fileInfo.getFileName()));
                }else{
                    fileInfo.setChecked(!fileInfo.isChecked());
                    CheckBox cb = view.findViewById(R.id.cb);
                    cb.setChecked(fileInfo.isChecked());
                }
            }
        });
    }

    protected void onBackMain() {
        View tvBackMain = multipleStatusView.findViewById(R.id.tv_back_main);
        if(tvBackMain!=null) tvBackMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startIconAnim(v);
                act.finish();
            }
        });
    }

    public void onAdmin(){
        isEdit = !isEdit;
        adp.setEdit(isEdit);
        if (!isEdit) setCancelStatus();
        adp.notifyDataSetChanged();
        ((DownloadAct)act).tvEdit.setText(isEdit ? "取消" : "编辑");
        llBottomEdit.setVisibility(isEdit ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setData() {

    }

    @OnClick({R.id.tv_confirm, R.id.tv_delete})
    public void onEdit(View view) {
        startIconAnim(view);
        switch (view.getId()) {
            case R.id.tv_confirm://全选
                isSelectedAll = !isSelectedAll;
                tvConfirm.setText(isSelectedAll ? "不选" : "全选");
                for (int i = 0; i < fileList.size(); i++) {
                    fileList.get(i).setChecked(isSelectedAll);
                }
                adp.notifyDataSetChanged();
                break;
            case R.id.tv_delete://删除
                int count = 0;
                for (int i = 0; i < fileList.size(); i++) {
                    if(fileList.get(i).isChecked())count++;
                }
                if(count==0){
                    showToast("没有选择项，无法删除！");
                    return;
                }
                RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(act);
                rxDialogSureCancel.getTitleView().setVisibility(View.GONE);
                rxDialogSureCancel.setContent("确定要删除"+count+"项吗？");
                rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteDatas();
                        rxDialogSureCancel.dismiss();
                    }
                });
                rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        rxDialogSureCancel.dismiss();
                    }
                });
                rxDialogSureCancel.show();
                break;
        }

    }

    private void deleteDatas() {
        List<FileInfo> removeDatas = new ArrayList<>();
        for (int i = 0; i < fileList.size(); i++) {
            FileInfo bean = fileList.get(i);
            if (bean.isChecked()) {
                removeDatas.add(bean);
            }
        }
        fileList.removeAll(removeDatas);
        for (int i = 0; i < removeDatas.size(); i++) {
            FileInfo bean = removeDatas.get(i);
            if (bean.isChecked()) {
                fileInfoDao.delete(bean);
            }
        }
        setCancelStatus();
    }

    private boolean isSelectedAll = false;

    private void setCancelStatus() {
        for (int i = 0; i < fileList.size(); i++) {
            fileList.get(i).setChecked(false);
        }
        isEdit = false;
        adp.setEdit(isEdit);
        adp.notifyDataSetChanged();
        llBottomEdit.setVisibility(View.GONE);
        ((DownloadAct)act).tvEdit.setText(fileList.size() > 0 ? "编辑" : "");
        if(fileList.size()==0){
            multipleStatusView.showEmpty();
            onBackMain();
        }
    }

}
